<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { QuestionFilled } from '@element-plus/icons-vue'
import { useAddOrEditInvoiceTitle, useGetMemberInfo } from '@fl/api/member-api'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { cloneDeep } from 'lodash-es'

import { INVOICE_TYPE, INVOICE_TYPE_OPTIONS } from '../constant'

const props = defineProps<{
    invoiceTitleData: any
}>()
const visible = defineModel<boolean>('visible', { required: true })

const initialState = {} as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!props.invoiceTitleData)
const dialogTitle = computed(() => isEdit.value ? '编辑发票抬头' : '新建发票抬头')

const { isPending: isAddOrEditInvoiceTitlePending, mutate: addOrEditInvoiceTitle } = useAddOrEditInvoiceTitle()
const { data: memberInfoData, isLoading: isGetMemberInfoLoading } = useGetMemberInfo()

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isGetMemberInfoLoading.value)
const isSubmitLoading = computed(() => isAddOrEditInvoiceTitlePending.value)

const columns: PlusColumn[] = [
    {
        fieldProps: {
            disabled: true,
        },
        label: '发票抬头',
        prop: 'invoiceTitle',
        valueType: 'copy',
    },
    {
        label: '默认发票类型',
        options: INVOICE_TYPE_OPTIONS,
        prop: 'invoiceType',
        valueType: 'radio',
    },
    {
        label: '统一社会信用代码',
        prop: 'taxNo',
        valueType: 'copy',
    },
    {
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '开户银行名称',
        prop: 'bankName',
        valueType: 'copy',
    },
    {
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '基本开户账号',
        prop: 'bankAccount',
        valueType: 'copy',
    },
    {
        fieldProps: {
            maxlength: 50,
            showWordLimit: true,
        },
        label: '注册场所地址',
        prop: 'registerAddr',
        valueType: 'copy',
    },
    {
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '注册固定电话',
        prop: 'registerPhone',
        valueType: 'copy',
    },
]

const rules = computed(() => ({
    bankAccount: [
        {
            message: '请输入基本开户账号',
            required: state.value?.invoiceType === INVOICE_TYPE.VAT_INVOICE,
            trigger: ['change', 'blur'],
        },
    ],
    bankName: [
        {
            message: '请输入开户银行名称',
            required: state.value?.invoiceType === INVOICE_TYPE.VAT_INVOICE,
            trigger: 'change',
        },
    ],
    invoiceTitle: [
        {
            message: '请输入发票抬头',
            required: true,
            trigger: 'change',
        },
    ],
    invoiceType: [
        {
            message: '请选择发票类型',
            required: true,
            trigger: 'change',
        },
    ],
    registerAddr: [
        {
            message: '请输入注册场所地址',
            required: state.value?.invoiceType === INVOICE_TYPE.VAT_INVOICE,
            trigger: ['change', 'blur'],
        },
    ],
    registerPhone: [
        {
            message: '请输入注册固定电话',
            required: state.value?.invoiceType === INVOICE_TYPE.VAT_INVOICE,
            trigger: 'change',
        },
        {
            message: '无效的固定电话号码',
            pattern: /^(\(0\d{2,3}\)|0\d{2,3}-)?\d{7,8}$/,
            trigger: 'change',
        },
    ],
    taxNo: [
        {
            message: '请输入统一社会信用代码',
            required: true,
            trigger: 'change',
        },
        {
            message: '无效的统一社会信用代码',
            pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/,
            trigger: 'change',
        },
    ],
}))

watch(
    () => state.value?.invoiceType,
    () => {
        formRef.value.formInstance.clearValidate()
    },
)

function submit() {
    const params = {
        ...state.value,
    }
    addOrEditInvoiceTitle(params, {
        onSuccess() {
            ElMessage.success('操作成功')
            cancel()
        },
    })
}
// #endregion

// #region UI Listener
function onSubmitBtnClick() {
    formRef.value.handleSubmit()
}

function onCreditCodeExampleBtnClick() {

}

function cancel() {
    visible.value = false
}

function closed() {
    state.value = cloneDeep(initialState)
    formRef.value?.formInstance?.resetFields()
}

function open() {
    state.value = cloneDeep(props.invoiceTitleData) || {}
}
// #endregion

watchEffect(() => {
    if (!isEdit.value) {
        Object.assign(state.value, {
            invoiceTitle: memberInfoData.value?.companyName,
            taxNo: memberInfoData.value?.taxNo,
        })
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                close-on-press-escape
                width="800"
                @cancel="cancel"
                @closed="closed"
                @open="open"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="140"
                  :rules="rules"
                  :has-footer="false"
                  :row-props="{ gutter: 40 }"
                  @submit="submit"
        >
            <template #plus-field-taxNo>
                <div class="flex items-center">
                    <el-input v-model="state.taxNo"
                              placeholder="请输入统一社会信用代码"
                    />

                    <el-icon :size="16"
                             color="white"
                             class="ml-16 bg-[#409eff] rounded-full"
                    >
                        <QuestionFilled />
                    </el-icon>

                    <el-button text
                               type="primary"
                               class="!p-4 !text-[#409eff]"
                               @click="onCreditCodeExampleBtnClick"
                    >
                        范例：统一社会信用代码
                    </el-button>
                </div>

                <div class="mt-8 text-[12px] text-[#aaa] leading-[12px]">
                    请与贵公司财务人员核实后，仔细填写准确的三证合一后的社会统一信用代码，否则将影响后续发票的正常使用
                </div>
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    提交
                </SubmitBtn>

                <el-button @click="cancel">
                    取消
                </el-button>
            </div>
        </template>
    </PlusDialog>
</template>

<style lang="scss" scoped>
:deep(.el-input) {
    width: 420px;
}
</style>
